//
//  GradientView.m
//  iOSStudy
//
//  Created by Evan Xie on 12/4/15.
//  Copyright © 2015 Family Wings. All rights reserved.
//

#import "GradientView.h"

@implementation GradientView

- (void)drawLinearGradient:(CGContextRef)context inRect:(CGRect)rect
{
    CGColorSpaceRef colorSpace;
    CGGradientRef gradient;
    
    // Draw Linear Gradient
    CGFloat locations[2] = { 0.0, 1.0 };
    CGFloat components[8] = {
        1.0, 0.5, 0.4, 1.0, // Start color
        0.8, 0.8, 0.3, 1.0  // End color
    };
    
    CGPoint myStartPoint, myEndPoint;
    myStartPoint.x = 0;
    myStartPoint.y = 50;
    myEndPoint.x = rect.size.width;
    myEndPoint.y = 50;
    
    colorSpace = CGColorSpaceCreateDeviceRGB();
    gradient = CGGradientCreateWithColorComponents(colorSpace, components, locations, 2);
    CGColorSpaceRelease(colorSpace);
    
    CGContextSaveGState(context);
    CGContextClipToRect(context, rect);
    CGContextDrawLinearGradient(context, gradient, myStartPoint, myEndPoint, 0);
    CGGradientRelease(gradient);
    CGContextRestoreGState(context);
}

- (void)drawRadialGradient:(CGContextRef)context inRect:(CGRect)rect
{
    CGPoint myStartPoint, myEndPoint;
    CGFloat myStartRadius, myEndRadius;
    myStartPoint.x = CGRectGetMinX(rect) + 40;
    myStartPoint.y = CGRectGetMaxY(rect) - 40;
    myEndPoint.x = CGRectGetMaxX(rect) - 60;
    myEndPoint.y = CGRectGetMinY(rect) + 60;
    myStartRadius = 30;
    myEndRadius = 50;
    
    CGFloat locations[2] = { 0.0, 1.0 };
    CGFloat components[8] = {
        1.0, 0.0, 1.0, 1.0, // Start color
        0.0, 1.0, 1.0, 1.0  // End color
    };

    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGGradientRef gradient = CGGradientCreateWithColorComponents(colorSpace, components, locations, 2);
    CGColorSpaceRelease(colorSpace);
    
    CGContextSaveGState(context);
    CGContextClipToRect(context, rect);
    CGContextDrawRadialGradient (context,
                                 gradient,
                                 myStartPoint,
                                 myStartRadius,
                                 myEndPoint,
                                 myEndRadius,
                                 0);
    CGGradientRelease(gradient);
    CGContextRestoreGState(context);
}

- (void)drawRect:(CGRect)rect
{
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetAllowsAntialiasing(context, true);
    CGContextSetShouldAntialias(context, true);
    
    [self drawLinearGradient:context inRect:CGRectMake(0, 0, rect.size.width, 60)];
    [self drawRadialGradient:context inRect:CGRectMake(0, 70, rect.size.width, 150)];
}

@end
